package com.fgsecure.apjhnou.app;

import java.io.File;
import java.io.IOException;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.fgsecure.apjhnou.adapter.CategoryAdapter;
import com.fgsecure.apjhnou.info.Global;
import com.fgsecure.apjhnou.quickactions.ActionItem;
import com.fgsecure.apjhnou.quickactions.QuickAction;

public class ItemActivity extends Activity {
	private ListView listViewItem;
	private Vector<Object> vItem;
	private Vector<String> vItemUrl;
	final Context context = this;
	private static final int ID_UP = 1;
	private static final int ID_DOWN = 2;
	private static final int ID_NEW = 3;
	private static final int ID_EDIT = 4;
	private static final int ID_DEL = 5;
	private int positionLongClick = 0;
	String[] values = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.listview_item);
		initData();
	}

	public void initData() {
		vItem = Global.getvObj();
		values = new String[vItem.size() / 2];
		Integer valuesNum = 0;
		vItemUrl = new Vector<String>();
		for (int i = 0; i < vItem.size(); i = i + 2) {
			values[valuesNum++] = (String) vItem.get(i);
			vItemUrl.add((String) vItem.get(i + 1));
		}
		CategoryAdapter adapter = new CategoryAdapter(this,
				R.layout.listview_item_row, values);
		listViewItem = (ListView) findViewById(R.id.listViewItem);
		View header = (View) getLayoutInflater().inflate(
				R.layout.listview_header_row, null);
		listViewItem.addHeaderView(header);
		listViewItem.setAdapter(adapter);
		final Intent intent = new Intent(this, ViewItemActivity.class);
		ActionItem downItem = new ActionItem(ID_DOWN, "Down", getResources()
				.getDrawable(R.drawable.menu_down_arrow));
		ActionItem upItem = new ActionItem(ID_UP, "Up", getResources()
				.getDrawable(R.drawable.menu_up_arrow));
		ActionItem addItem = new ActionItem(ID_NEW, "New", getResources()
				.getDrawable(R.drawable.menu_add));
		ActionItem editItem = new ActionItem(ID_EDIT, "Edit", getResources()
				.getDrawable(R.drawable.menu_edit));
		ActionItem delItem = new ActionItem(ID_DEL, "Delete", getResources()
				.getDrawable(R.drawable.menu_del));

		final QuickAction quickAction = new QuickAction(this,
				QuickAction.HORIZONTAL);

		// add action items into QuickAction
		quickAction.addActionItem(addItem);
		quickAction.addActionItem(editItem);
		quickAction.addActionItem(delItem);

		// Set listener for action item clicked
		quickAction
				.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
					@Override
					public void onItemClick(QuickAction source, int pos,
							int actionId) {
						ActionItem actionItem = quickAction.getActionItem(pos);
						// here we can filter which action item was clicked with
						// pos or actionId parameter
						if (actionId == ID_NEW) {
							dialogAdd();
						} else if (actionId == ID_EDIT) {
							if (positionLongClick != 0)
								dialogEdit();
						} else if (actionId == ID_DEL) {
							if (positionLongClick != 0)
								dialogDelete();
						}
					}
				});

		listViewItem.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> adapter, View view,
					int position, long id) {
				positionLongClick = position;
				quickAction.show(view);
				return false;
			}
		});
		listViewItem.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position > 0) {
					intent.putExtra("uri", (String) vItemUrl.get(position - 1));
					startActivity(intent);
				}

			}
		});
	}

	public void addItem(String name) throws ParserConfigurationException,
			SAXException, IOException, TransformerException {
		File fXmlFile = new File("/sdcard/MyFile/myFile.xml");
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = null;
		Document doc = null;
		dBuilder = dbFactory.newDocumentBuilder();
		doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();
		Element root = doc.getDocumentElement();
		Element category = (Element) root.getElementsByTagName("category")
				.item(Global.getCategory());
		Element subject = (Element) category.getElementsByTagName("subject")
				.item(Global.getSubject());
		Element lesson = (Element) subject.getElementsByTagName("lessons")
				.item(Global.getLesson());
		Element item = doc.createElement("item");
		item.setAttribute("name", name);
		item.setAttribute("location", "location");
		lesson.appendChild(item);
		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(fXmlFile);
		transformer.transform(source, result);
	}

	public void delItem() throws ParserConfigurationException, SAXException,
			IOException, TransformerException {
		File fXmlFile = new File("/sdcard/MyFile/myFile.xml");
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = null;
		Document doc = null;
		dBuilder = dbFactory.newDocumentBuilder();
		doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();
		Element root = doc.getDocumentElement();
		Element category = (Element) root.getElementsByTagName("category")
				.item(Global.getCategory());
		Element subject = (Element) category.getElementsByTagName("subject")
				.item(Global.getSubject());
		Element lesson = (Element) subject.getElementsByTagName("lessons")
				.item(Global.getLesson());
		NodeList nList = lesson.getElementsByTagName("item");
		Node nNode = nList.item(positionLongClick - 1);
		lesson.removeChild(nNode);
		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(fXmlFile);
		transformer.transform(source, result);
	}

	public void editItem(String name) throws ParserConfigurationException,
			SAXException, IOException, TransformerException {
		File fXmlFile = new File("/sdcard/MyFile/myFile.xml");
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = null;
		Document doc = null;
		dBuilder = dbFactory.newDocumentBuilder();
		doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();
		Element root = doc.getDocumentElement();
		Element category = (Element) root.getElementsByTagName("category")
				.item(Global.getCategory());
		Element subject = (Element) category.getElementsByTagName("subject")
				.item(Global.getSubject());
		Element lesson = (Element) subject.getElementsByTagName("lessons")
				.item(Global.getLesson());
		NodeList nList = lesson.getElementsByTagName("item");
		Node nNode = nList.item(positionLongClick - 1);
		Element eElement = (Element) nNode;
		eElement.setAttribute("name", name);
		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(fXmlFile);
		transformer.transform(source, result);
	}

	private void restartFirstActivity() {
		Vector<Object> menu = Global.readXML();
		Vector<Object> vSubject = (Vector<Object>) menu.get(Global
				.getCategory() * 2 + 1);
		Vector<Object> vLessons = (Vector<Object>) vSubject.get(Global
				.getSubject() * 2 + 1);
		Vector<Object> item = (Vector<Object>) vLessons
				.get(Global.getLesson() * 2 + 1);
		Global.setvObj(item);
		Intent intent = getIntent();
		finish();
		startActivity(intent);
	}

	public void dialogAdd() {
		// get prompts.xml view
		LayoutInflater li = LayoutInflater.from(context);
		View promptsView = li.inflate(R.layout.prompts_category, null);

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				context);

		// set prompts.xml to alertdialog builder
		alertDialogBuilder.setView(promptsView);
		TextView typeText = (TextView) promptsView
				.findViewById(R.id.typeTextTextView);
		typeText.setText(context.getString(R.string.text_subject));
		final EditText userInput = (EditText) promptsView
				.findViewById(R.id.editTextDialogUserInput);

		// set dialog message
		alertDialogBuilder
				.setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// get user input
						try {
							addItem(userInput.getText().toString().trim());
						} catch (ParserConfigurationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SAXException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (TransformerException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						restartFirstActivity();
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});

		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();

		// show it
		alertDialog.show();
	}

	public void dialogDelete() {
		// get prompts.xml view
		LayoutInflater li = LayoutInflater.from(context);
		View promptsView = li.inflate(R.layout.prompts_delete, null);
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				context);
		// set prompts.xml to alertdialog builder
		alertDialogBuilder.setView(promptsView);
		TextView typeText = (TextView) promptsView
				.findViewById(R.id.itemDelTextView);
		typeText.setText(values[positionLongClick - 1]);
		// set dialog message
		alertDialogBuilder
				.setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// get user input
						try {
							delItem();
						} catch (ParserConfigurationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SAXException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (TransformerException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						restartFirstActivity();
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();
		// show it
		alertDialog.show();
	}

	public void dialogEdit() {
		// get prompts.xml view
		LayoutInflater li = LayoutInflater.from(context);
		View promptsView = li.inflate(R.layout.prompts_category, null);
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				context);
		// set prompts.xml to alertdialog builder
		alertDialogBuilder.setView(promptsView);
		TextView typeText = (TextView) promptsView
				.findViewById(R.id.typeTextTextView);
		typeText.setText(context.getString(R.string.text_category));
		final EditText userInput = (EditText) promptsView
				.findViewById(R.id.editTextDialogUserInput);
		userInput.setText(values[positionLongClick - 1]);
		userInput.selectAll();
		// set dialog message
		alertDialogBuilder
				.setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// get user input
						try {
							editItem(userInput.getText().toString().trim());
						} catch (ParserConfigurationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SAXException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (TransformerException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						restartFirstActivity();
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();
		// show it
		alertDialog.show();
	}
}